package com.lzx.RandomForest;

import com.lzx.reader.DataReader;
import com.lzx.utils.GetMap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 如寄
 * @version: v1.0
 * @description: com.新闻分类.RandomForest
 * @date:2021/5/20
 */
public class RandomForestTrain {
    private GetMap getMap = new GetMap();
    private Map<String,Integer>feathers=new HashMap<>();
    private List<String>featherList=new ArrayList<>();
    /**
     * trainDataFile：训练数据文件
     * testDataFile：测试数据文件，主要用于过拟合处理
     * treeAmount：森林中树的数量
     * outputPath:模型输出路径
     */
    public void createForest(File trainDataFile, File testDataFile, Integer treeAmount,String outputPath) throws Exception {
        System.out.println("开始读训练数据！");
        Map<String, List<Map<Integer, Boolean>>> trainData = readData(trainDataFile);
        System.out.println("开始读测试数据！");
        Map<String, List<Map<Integer, Boolean>>> testData = readData(testDataFile);
        List<String> trees = new ArrayList<>();
        for (int i = 0; i < treeAmount; i++) {
            CreateTree createTree = new CreateTree();
            String tree = createTree.buildTree(trainData, testData,featherList);
            trees.add(tree);
            System.out.println(i);
        }
        FileWriter fileWriter = new FileWriter(new File(outputPath+"\\model.txt"));
        for (String tree : trees) {
            fileWriter.write(tree + "\n");
        }
        fileWriter.close();
    }

    /**
     * 在dir目录下，读取与classType数组同名的xlsx文件，读取其新闻数据
     *
     * @param filepath :数据源
     * @throws Exception
     * @return：数据集
     */
    private Map<String, List<Map<Integer, Boolean>>> readData(File file) throws Exception {
        Map<String, List<Map<Integer, Boolean>>> ans = new HashMap<>();
        InputStream resourceAsStream = new FileInputStream(file);
        Map<String, List<List<String>>> data = DataReader.readCSV(resourceAsStream);
        for (Map.Entry<String, List<List<String>>> entry : data.entrySet()) {
            List<List<String>> value = entry.getValue();
            Map<Integer, Boolean> map;
            List<Map<Integer, Boolean>> temp = new ArrayList<>();
            for (List<String> list : value) {
                map = getMap.toMap(list.get(0)+","+list.get(1),feathers,featherList);
                temp.add(map);
            }
            System.out.println("已处理:" + value.size() + "条数据");
            ans.put(entry.getKey(), temp);
        }
        return ans;
    }
}
